
# from cgi import logfile

import matplotlib.pyplot as plt
import datetime

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from xgboost import XGBClassifier

from log import Logger
from common import data_preprocessing
from sklearn.metrics import  roc_auc_score
import joblib



plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.size'] = 15

class Attrition_prediction:
    def __init__(self,path):
        # 1、配置日志
        logfile_name = "predict_" + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        self.logger = Logger("./", logfile_name).get_logger()
        # 2、获取数据源
        self.data_source = data_preprocessing(path)

# def predict(data,logger):
#     data = data_preprocessing('../../data/raw/test2.csv')
#     # print(data.head(10))
#     x = data.iloc[:, 1:]
#     y = data['Attrition']
#     # print(x)
#     # print(y)
#     es= joblib.load('Attrition_xgb.pkl')
#
#     y_pre = es.predict(x)
#     print(f'预测结果为{y_pre}')
#     # print(accuracy_score(y,y_pre))
#     my_roc_auc_score = roc_auc_score(y, y_pre)
#     print(f'auc值{my_roc_auc_score}')
#     # logger.info(accuracy_score(y,y_pre))


def predict(data,logger):
    x = data.iloc[:,1:]
    y = data['Attrition']
    # print(x)
    x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=25,stratify=y)
    #标准化
    transfer = StandardScaler()
    x_train = transfer.fit_transform(x_train)
    x_test  = transfer.transform(x_test)
    # #定义超参字典
    # param_dict={
    #     'n_estimators':[50,100,150,200],
    #     'max_depth':[3,5,6,7],
    #     'learning_rate':[0.01,0.1]
    # }
    #
    # # xgboost模型
    # es = XGBRegressor()
    # # 创建网格搜索
    # gs_es = GridSearchCV(es,param_grid=param_dict,cv=5)
    # #模型训练
    # gs_es.fit(x_train,y_train)
    #打印最优超惨组合
    # logger.info(f'最优参数组合:{gs_es.best_params_}')

    es = XGBClassifier(learning_rate= 0.1, max_depth=3, n_estimators= 50)
    es.fit(x_train,y_train)

    y_pre = es.predict_proba(x_test)[:,1]

    print(f"预测值：{y_pre}")
    # print(f'分类评估报告{classification_report(y_test, y_pre)}')
    # print(f'准确率{accuracy_score(y_test, y_pre)}')
    # print(f'混淆矩阵{confusion_matrix(y_test, y_pre)}')
    my_roc_auc_score = roc_auc_score(y_test,y_pre)
    print(f'auc值{my_roc_auc_score}')

if __name__ == '__main__':
    at = Attrition_prediction('../../data/raw/test2.csv')
    predict(at.data_source,at.logger)

